/***
* description:中间表主表，处理ＰＤＡ上传上来的数据
* modify history:
* 1、Fuhaisha  2011-5-25   添加活动订单逻辑
* 2、huangxiaojiang 2011-6-23 增加经销商订单数据同步功能
*/
Trigger InsertToVisitAndOrder on VisitAndOrderInProcess__c (before insert) {
    
    list<Account>lUpdateAccount=new list<Account>();//需要更标准坐标的门店
    
    Set<Id> IdList=new Set<Id>();
    Set<Date> DateList=new Set<Date>();
    
    //列表存储当前用户信息及用户manager信息 by xiaojiang 6-23
    user curUser;
    user managerUser;
    id idASM;//当前用户对应的ASM角色的上级用户的id
    final string titleASM='Area/District Sales Manager';
    //final string titleTSR='Sales Rep';
    //final string titleSupervisor='Sales Supervisor';
    //有些tsr的manager是ASM角色，有些的manager是supervisor这时要越级找到ASM角色上级用户id
    if(trigger.new.size()>0){
        list<user> lUser=[select id,MANAGERID from user where id=:userInfo.getUserId()];
        if(lUser.size()>0){
             curUser=lUser[0];    
        }
       
        if(curUser!=null){
            lUser=[select id,TITLE,MANAGERID from user where id=:curUser.MANAGERID];
            if(lUser.size()>0){
                managerUser=lUser[0];
                if(managerUser.title==titleASM){
                    idASM=managerUser.id;    
                }else{
                     lUser=[select id,TITLE,MANAGERID from user where id=:managerUser.MANAGERID];
                     if(lUser.size()>0){
                         managerUser=lUser[0];
                        if(managerUser.title==titleASM){
                            idASM=managerUser.id;    
                        }                             
                     }    
                }
            }
        }
       
        
    }
        
    
    for(VisitAndOrderInProcess__c vop:trigger.new)
    {
        IdList.add(vop.Outlet__c);
        DateList.add(vop.StartTime__c.Date());
    }
    //处理routing plan and visit
    List<Routing_Plan_And_Visit__c> rpavList=[select Id,Visit_Date__c from Routing_Plan_And_Visit__c 
                                              where Visit_Date__c in:DateList and OwnerId=:UserInfo.getUserId()];
    
    Map<Date,Id> rpavMapList=new Map<Date,Id>();
    for(Routing_Plan_And_Visit__c rpav:rpavList)
    {
        rpavMapList.put(rpav.Visit_Date__c,rpav.Id);
    }
    List<Routing_Plan_And_Visit__c> InsertRPAVList=new List<Routing_Plan_And_Visit__c>();
    for(Date d:DateList)
    {
        if(!rpavMapList.containsKey(d))
        {
            Routing_Plan_And_Visit__c rC=new Routing_Plan_And_Visit__c(Visit_Date__c=d,OwnerId=UserInfo.getUserId());
            InsertRPAVList.add(rC);
        }
    }
    insert InsertRPAVList;
    
    for(Routing_Plan_And_Visit__c rp:InsertRPAVList)
    {
        rpavMapList.put(rp.Visit_Date__c,rp.Id);
    }
    
    //处理Routing Plan
    List<RoutingPlan__c> rpList=[select Id,OutletName__c,StartDateTime__c,Plan_Visit_Date__c from RoutingPlan__c where 
                                  OutletName__c in:IdList and Plan_Visit_Date__c in:DateList];
    Map<String,Id> RoutingPlanList=new Map<String,Id>();
    for(RoutingPlan__c rp:rpList)
    {
        RoutingPlanList.put(rp.OutletName__c+String.valueOf(rp.Plan_Visit_Date__c),rp.Id);
        rp.PlanStatus__c='done';
    }
    update rpList;
    
    //处理in store visit
    List<In_Store_Visit__c>  VList=[select Id,StartDate__c,OutletName_del__c,Start_Time__c,End_Time__c from In_Store_Visit__c 
                                   where StartDate__c in:DateList and OutletName_del__c in:IdList 
                                   and RoutingPlanAndVisit__r.OwnerId=:UserInfo.getUserId()];
                                   
    Map<String,In_Store_Visit__c> istMapList=new Map<String,In_Store_Visit__c>();
    for(In_Store_Visit__c isv:VList)
    {
        istMapList.put(isv.OutletName_del__c+String.valueOf(isv.StartDate__c),isv);
    }
    
    Map<String,In_Store_Visit__c> UpdateMapList=new Map<String,In_Store_Visit__c>();
    Map<String,Id> InStoreVisitId=new Map<String,Id>();
    Map<String,In_Store_Visit__c> InsertMapList=new Map<String,In_Store_Visit__c>();
    Map<String,In_Store_Visit__c> InsertMapList2=new Map<String,In_Store_Visit__c>();
    set<string> hasNotPerformed=new set<string>();//保存没有执行促销形式的ID
    set<string> hasPerformed=new set<string>();//保存有执行的促销形式的ID
    
    for(VisitAndOrderInProcess__c pro:trigger.new)
    {
        String key=pro.Outlet__c+String.valueOf(pro.StartTime__c.Date());
        //if(pro.Type__c=='In Store Visit')
        //{
            if(istMapList.containsKey(Key))
            {
                if(pro.Type__c=='In Store Visit')
                {
                    if(pro.HasNotPerformedCompetionBrandInfoID__c!=NULL)
                    {
                        List<string> strList=String.valueOf(pro.HasNotPerformedCompetionBrandInfoID__c).split(';');
                        for(string str:strList)
                            hasNotPerformed.add(str);
                    }
                    if(pro.HasPerformedCompetionBrandInfoID__c!=NULL)
                    {
                        List<string> strList=String.valueOf(pro.HasPerformedCompetionBrandInfoID__c).split(';');
                        for(string str:strList)
                            hasPerformed.add(str);
                    }
                    
                    In_Store_Visit__c v=istMapList.get(key);
                    v.MainShelfDisplayIsStandard__c=pro.MainShelfDisplayIsStandard__c;
                    v.SSYActivityAchievement__c=pro.SSYActivityExecution__c;
                    //v.Start_Time__c=pro.StartTime__c;
                    //v.End_Time__c=pro.EndTime__c;
                    v.OutletName_del__c=pro.Outlet__c;
                    v.SSY_Promotion_TSR__c=pro.SSY_Promotion_TSR__c;
                    v.KA_Promotion_TSR__c=pro.KA_Promotion_TSR__c;
                    v.Other_Promotion_TSR__c=pro.Other_Promotion_TSR__c;
                   // v.RoutingPlanItem__c=pro.RoutingPlan__c;
                   
                   //修改店面拜访信息时,更新美赞臣促销活动及非门店拜访相关信息 by xiaojiang 20110413
                   if(pro.NationalPromotion__c!=null){
                       if(pro.NationalPromotion__c.length()>0){
                           v.NationalPromotion__c=pro.NationalPromotion__c;
                       }                   
                   }else{
                         v.NationalPromotion__c=null;
                   }

                   
                   //只要全国活动不为空，ssyExecution为ture byxiaojiang 20110516
                   if(v.NationalPromotion__c!=null){
                       if(v.NationalPromotion__c.length()>0){
                           v.SSYActivityAchievement__c=true;    
                       }else{
                           v.SSYActivityAchievement__c=false;    
                       }                   
                   }                  
                   if(pro.KAPromotion__c!=null){
                       if(pro.KAPromotion__c.length()>0){
                            v.KAPromotion__c=pro.KAPromotion__c;
                       }                   
                   }else{
                       v.KAPromotion__c=null;
                   }
                                     
                   if(pro.OtherPromotion__c!=null){
                        if(pro.OtherPromotion__c.length()>0){
                          v.OtherPromotion__c=pro.OtherPromotion__c; 
                       }                  
                   }else{
                       v.OtherPromotion__c=null;
                   }
                                  
                    UpdateMapList.put(Key,v);
                    
                }else{
                
                    if(pro.Type__c==null){//非门店拜访 by xiaojiang 20110516
                       if(pro.OutletType__c=='客户办公室'){                           
                           In_Store_Visit__c v=istMapList.get(key);
                           v.OutletName_del__c=pro.Outlet__c; 
                           if(pro.jobItems__c!=null){
                               if(pro.jobItems__c.length()>0){
                                   v.jobItems__c=pro.jobItems__c;
                               }                        
                           }else{
                                v.jobItems__c=null;   
                           }

                          UpdateMapList.put(Key,v);
                       }                    
                    }
                }
               
            }
            else
            {
                Id IdStr=rpavMapList.get(pro.StartTime__c.Date());//获取routing plan and visit的ID
                 if(IdStr!=NULL)
                 {
                    Id rpId=RoutingPlanList.get(Key);//获取routing plan的ID
                    //新建门店拜访时，根据phaseII需求把中间表的美赞臣促销活动，非门店拜访，当前拜访坐标都回传 by xiaojiang 20110413
                   
                    //存储需要更新的标准坐标的门店
                    if(pro.IsConfirm__c==false&&pro.lat__c!=null&&pro.lon__c!=null){
                        lUpdateAccount.add(new Account(id=pro.Outlet__c,lat__c=pro.lat__c,lon__c=pro.lon__c,IsConfirm__c=true));
                    }
                    
                    In_Store_Visit__c is=new In_Store_Visit__c(lat__c=pro.lat__c,lon__c=pro.lon__c,NationalPromotion__c=pro.NationalPromotion__c,
                    KAPromotion__c=pro.KAPromotion__c,OtherPromotion__c=pro.OtherPromotion__c,
                    MainShelfDisplayIsStandard__c=pro.MainShelfDisplayIsStandard__c,
                    SSYActivityAchievement__c=pro.SSYActivityExecution__c,Start_Time__c=pro.StartTime__c,End_Time__c=pro.EndTime__c,
                    RoutingPlanAndVisit__c=IdStr,OutletName_del__c=pro.Outlet__c,RoutingPlanItem__c=rpId,
                     SSY_Promotion_TSR__c=pro.SSY_Promotion_TSR__c,
                    KA_Promotion_TSR__c=pro.KA_Promotion_TSR__c,
                    Other_Promotion_TSR__c=pro.Other_Promotion_TSR__c);
                     
                     if(pro.OutletType__c=='客户办公室'){
                         is.jobItems__c=pro.jobItems__c;
                     }
                   //只要全国活动不为空，ssyExecution为ture byxiaojiang 20110516
                   if(pro.NationalPromotion__c!=null){
                       if(pro.NationalPromotion__c.length()>0){
                            is.SSYActivityAchievement__c=true;
                       }else{
                           is.SSYActivityAchievement__c=false;
                       }
                      
                   }                     
                                    
                    if(pro.Type__c=='In Store Visit')
                    {
                         
                         InsertMapList.put(Key,is);
                    }
                    else
                    {
                        InsertMapList2.put(Key,is);
                    }
                 }
            }
        //}
        if(istMapList.get(Key)!=NULL)
        {
            In_Store_Visit__c v=istMapList.get(Key);
            InStoreVisitId.put(Key,v.Id);
        }
    }
    
    for(In_Store_Visit__c ivs:InsertMapList2.values())
    {
        String key=ivs.OutletName_del__c+String.valueOf(ivs.Start_Time__c.Date());
        if(!InsertMapList.containsKey(key))
        {
            InsertMapList.put(Key,ivs);
        }
    }
    
    //更新门店标准坐标,先更新门店坐标才能在instoreVisit里面计算偏差值
    if(lUpdateAccount.size()>0){
        update lUpdateAccount;
    }
    
    update UpdateMapList.values();
    insert InsertMapList.values();
    for(In_Store_Visit__c ivs:InsertMapList.values())
    {
        String key=ivs.OutletName_del__c+String.valueOf(ivs.Start_Time__c.Date());
        InStoreVisitId.put(Key,ivs.Id);
    }
    
    list<recordtype> rlist=new list<recordtype>();
    id returnorder;
    id freegoods;
    id normal;
    id activityOrder;
    id shipmentOrder;
    id distributorReturnOrder;    
    
    rlist=[select id,DeveloperName from recordtype where sobjecttype=:'order__c' and ( DeveloperName=:'FreeGoodsOrder' or DeveloperName=:'NormalOrder' or DeveloperName=:'ReturnOrder' or DeveloperName=:'ActivityOrder')];

    for(recordtype rt:rlist){    //匹配recordtypeid
        if(rt.DeveloperName=='freegoodsorder'){
            freegoods=rt.id;
        }else if(rt.DeveloperName=='normalorder'){
            normal=rt.id;
        }else if(rt.DeveloperName=='returnorder'){
            returnorder=rt.id;
        }
        else if(rt.DeveloperName=='ActivityOrder')
        {
            activityOrder=rt.id;
        }else if(rt.DeveloperName=='ShipmentOrder'){//add by xiaojiang 6-23
            shipmentOrder=rt.id;
        }else if(rt.DeveloperName=='DistributorReturnOrder'){
            distributorReturnOrder=rt.id;
        }
    }
    
    Map<Integer, Order__c> orderRelationMap = new Map<Integer, Order__c>();
    List<In_Store_Visit__c> delComStore = new List<In_Store_Visit__c>();
    List<In_Store_Visit__c> delInvStore = new List<In_Store_Visit__c>();
    for(Integer i = 0; i < trigger.new.size(); i++)
    {
        VisitAndOrderInProcess__c all = trigger.new[i];
        Date dt=all.StartTime__c.Date();
        
        for(In_Store_Visit__c i1:InsertMapList.values())
        {
            Date vd=i1.Start_Time__c.Date();
            //Date vd=Date.newInstance(vdt.year(), vdt.month(), vdt.day());
            if(all.Outlet__c==i1.OutletName_del__c && dt==vd)
            {
                all.InStoreVisit__c=i1.Id;
                if(all.HasCompetitor__c){ // has Competitor, so add to list delComStore
                    delComStore.add(i1);
                }
                if(all.HasInventory__c){ // has Inventory, so add to list delInvStore 
                    delInvStore.add(i1);
                }
            }
        }
        
        for(In_Store_Visit__c i2:UpdateMapList.values())
        {
            DateTime vd=i2.Start_Time__c.Date();
            //Date vd=Date.newInstance(vdt.year(), vdt.month(), vdt.day());
            if(all.Outlet__c==i2.OutletName_del__c && dt==vd)
            {
                all.InStoreVisit__c=i2.Id;
                if(all.HasCompetitor__c){ // has Competitor, so add to list delComStore
                    delComStore.add(i2);
                }
                if(all.HasInventory__c){ // has Inventory, so add to list delInvStore 
                    delInvStore.add(i2);
                }
            }
           
        }
        if(InStoreVisitId.containsKey(all.Outlet__c+String.valueOf(dt)))
            all.InStoreVisit__c=InStoreVisitId.get(all.Outlet__c+String.valueOf(dt));
        
        if(all.Type__c=='Order')
        {
            Order__c ord=new Order__c();
            ord.Address__c=all.OutletAddress__c;
            ord.Distributor_Name__c=all.Distributor__c;
            ord.OrderType__c=all.OrderType__c;
            ord.OutletContact__c=all.OutletContact__c;
            ord.Order_date__c=all.OrderDate__c;
            ord.Time_to_delivered__c=all.DeliveryDate__c;
            ord.Phone__c=all.OutletPhone__c;
            ord.Outlet_name__c=all.Outlet__c;
            ord.Zip_Code__c=all.OutletZipCode__c;
            ord.In_Store_Visit__c=all.InStoreVisit__c;
            ord.SendOrderToDistributor__c=all.SendOrderToDistributor__c;
            ord.Activity_Information__c=all.Activity_Information__c;
            
            if(ord.OrderType__c=='常规')
                ord.RecordTypeId=normal;
            else if(ord.ordertype__c=='退货')
                ord.RecordTypeId=returnorder;
            else if(ord.ordertype__c=='免费产品')
                ord.RecordTypeId=freegoods;
             else if(ord.ordertype__c=='活动订单')
                 ord.RecordTypeId=activityOrder;
            //add by xiaojiang 6-23
            else if(ord.ordertype__c=='经销商订单'){
                 ord.RecordTypeId=shipmentOrder;
                 ord.DiscountOption__c=all.DiscountOption__c;
                 ord.DiscountRate__c=all.DiscountRate__c;
                 ord.ShipmentRemark__c=all.ShipmentRemark__c;
                 if(idASM!=null){
                     ord.ManageUser__c=idASM;
                 }              
             }
            else if(ord.ordertype__c=='经销商退订'){
                ord.RecordTypeId=distributorReturnOrder;
                 if(idASM!=null){
                     ord.ManageUser__c=idASM;
                 }                
            }
                             
            //ordList.add(ord);
            orderRelationMap.put(i, ord);
        }
        
       // d=null;
        dt=null;
    }  
    //insert ordList;
    insert orderRelationMap.values();
    
    for(Integer i = 0; i < trigger.new.size(); i++)
    {
        if(trigger.new[i].Type__c=='Order')
        {
            Order__c order = orderRelationMap.get(i);
            if(order != null)
            {
                trigger.new[i].Order__c = order.Id;
            }
       }
    } 
    
    List<Competitor__c> delCom =[Select id From Competitor__c Where in_store_visit__c in:delComStore];
    if(delCom.size() > 0){
        delete delCom;
    }
    List<Inventory__c> delInv =[Select id From Inventory__c Where In_Store_Visit__c in:delInvStore];
    if(delInv.size() > 0){
        delete delInv;
    }
    //更改竞品费用类型明细表状态
    if(hasNotPerformed.size()>0 || hasPerformed.size()>0)
    {
        //查出所有的记录
        List<Activity_Competition_Brand_Detail__c> acbdList=[select id,IsPerformance__c from Activity_Competition_Brand_Detail__c where id in:hasNotPerformed or id in:hasPerformed];
        for(Activity_Competition_Brand_Detail__c acbd:acbdList)
        {
            if(hasNotPerformed .contains(acbd.id))
                acbd.IsPerformance__c=false;
            if(hasPerformed.contains(acbd.id))
                acbd.IsPerformance__c=true;
        }    
        update acbdList;
    }
   // set<string> hasPerformed=new set<string>();//保存有执行的促销形式的ID
}